package utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5加密 工具类
 * Created by weijianyu on 2017/4/5.
 */
public class MD5Util {

    private static final Logger logger = LogManager.getLogger(MD5Util.class);

    private MD5Util() {
    }

    /**
     * md5加密
     *
     * @param encryptStr 明文
     * @return 32位密文 null为加密错误
     */
    public static String encrypt32(String encryptStr) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(encryptStr.getBytes());
            StringBuilder hexValue = new StringBuilder();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            logger.error("md5 加密错误!", e);
        }
        return null;
    }

    /**
     * @param encryptStr 明文
     * @return 16为密文
     */
    public static String encrypt16(String encryptStr) {
        return encrypt32(encryptStr).substring(8, 24);
    }
}
